package com.wang.listener;

import com.rabbitmq.client.Channel;
import com.wang.model.OrderMessage;
import com.wang.service.ProductOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.order_close_queue}")
public class OrderMQListener {
    @Autowired
    private ProductOrderService productOrderService;

    @RabbitHandler
    public void closeOrder(OrderMessage orderMessage, Message message, Channel channel) throws IOException {
        log.info("监听到消息：{}",orderMessage);
        long msgFlag = message.getMessageProperties().getDeliveryTag();

        try {
            boolean  result = productOrderService.closeOrder(orderMessage);
            if(result){
                channel.basicAck(msgFlag,false);
            }else{
                channel.basicReject(msgFlag,true);
            }
        } catch (Exception e) {
            log.error("订单关闭失败：{}",orderMessage);
            channel.basicReject(msgFlag,true);
        }
    }
}
